var express = require('express');
var router = express.Router();
const db = require("../db/index.js");
const { v4: uuidv4 } = require('uuid');
// 用这个包来生成 Token 字符串
const jwt = require("jsonwebtoken");
// 导入配置文件
const config = require("../config");
// 新增教练
router.post('/addCoach', function(req, res, next) {
  let info = req.body
  let token = req.headers.token
  jwt.verify(token, config.jwtSecretKey, function (err, result) {
    // console.log(result);
    if(result.role !== 'admin'){
        res.send({code:0,message:'您的权限不够'})
    }else{
        const sql = `select *from coach where username=?`
        db.query(sql,info.username,function(err,results){
            if(err)  res.send({code:0,message:err.message})
            if(results.length>0)  res.send({code:0,message:'该用户已经注册'})
            const sql1 = `insert into coach set ?`
            let ID = uuidv4()
            ID = ID.replace(/-/g, '')
            db.query(sql1 , {
                id:ID,
                username: info.username,
                password: info.password,
                nickname: info.nickname,
                phone: info.phone,
                age:info.age,
                gender:info.gender,
                photo:'https://www.qqkw.com/d/file/p/2022/12-08/da7df62bf2d7218e76cb01da67e68e30.jpg',
                role:'coach'
              },function(err,data){
                if(err)  res.send({code:0,message:err.message})
                res.send({code:200,message:'添加成功！'})
              })
            
        })
    }
  });
    
        
        
})

// 删除教练
router.post('/deleteCoach',function (req,res,next) {
  let token = req.headers.token
  let id = req.query.id
  
  jwt.verify(token, config.jwtSecretKey,function(err,data){
      if(data.role !== 'admin'){
          res.send({code:0,message:'您的权限不够'})
      }else{
          const sql = 'delete from coach where id=?'
          db.query(sql,id,function(err,result){
              if(err)  res.send({code:0,message:err.message})
              res.send({code:200,message:'删除成功！'})
          })
      }
  })

    
    
})

// 修改教练信息
router.post('/updateCoach',function(req,res,next){
  let token = req.headers.token
  let info = req.body
  console.log(info);
  jwt.verify(token, config.jwtSecretKey,function(err,data){
      if(err) res.send({code:0,message:err.message})
      if(data.role !=='admin')  res.send({code:0,message:'你没有权限做此操作!'})
      
      const sql = `update coach set username=?,nickname=?,password=?,age=? where id=? `
      db.query(sql,[info.username,info.nickname,info.password,info.age,info.id],function(err,result){
        if(err)  res.send({code:0,message:err.message})
        res.send({code:200,message:'修改成功!'})
      })
  })
})


// 查询教练列表
router.get('/coachList',function(req,res,next){
   console.log(req.query);
   // 获取参数   当前页码   当前每页数据量
   // 获取参数   当前页码   当前每页数据量
   let pageNumber = req.query.pageNumber
   // let pageSize = parseInt(req.body.pageSize)
   let pagesize = req.query.pagesize - 0
  // 求得sql语句中的参数
  console.log(pageNumber,pagesize);
 //  if(!pageNumber) pageNumber=1
 //  if(!pagesize) pagesize=6
  console.log(pageNumber,pagesize);
   let start = (pageNumber - 1) * pagesize
   // sql语句
   let sql = "select * from coach limit ?, ?"
   let sqlParam = [start, pagesize]
   let sqlCount = "select count(*) from coach"
 
   var count = 0
   // 执行查询
  db.query(sqlCount, null, (err, result) => {
    // 得到总记录数
    count = result[0]["count(*)"]
   
  })

  db.query(sql, sqlParam, (err, result) => {
    if (err) {
      res.send({
        code:0,
        message: err.message,
        ok:true
      })
    } else {
      res.send({
        code:200,
        message: "请求成功",
        ok: true,
        totalCount: count,
        data:result,
        
      })
    }
  })
    
})

// 查询教练详情
router.get('/getCoachInfo',function(req,res){
  console.log(req.query);
  let id = req.query.id
  const sql = `select * from coach where id=?`
  db.query(sql,id,function(err,results){
      if(err) res.send({code:0,message:err.message})
      res.send({code:200,message:'查询成功',data:results[0]})
  })
})

// 获取所有教练 
router.get('/allCoach',function(req,res,next){
  const sql = `select *from coach`
  db.query(sql,function(err,results){
    if(err) res.send({code:0,message:err.message})
      res.send({code:200,message:'查询成功',data:results})
  })
})

router.post('/search',function(req,res,next){
  let username  = req.body.username
  let nickname  = req.body.nickname
  let phone  = req.body.phone
  console.log(req.body);
  const sql =  `SELECT * FROM coach where username like '%${username}%' or nickname like '%${nickname}%' or phone like '%${phone}%'`
  db.query(sql,function(err,results){
    if(err) {return res.send({code:0,message:err.message})} 
    
    res.send({code:200,message:'查询成功!',data:results})
  })
})


module.exports = router;
